﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using Metrics.Head;

namespace Metrics.Utils
{
    class Diff
    {
        private static string diffFileName;

        public Diff(int fromRev, int toRev)
        {
            diffFileName = String.Format(@"{0}\{1}vs{2}.txt", Program.DiffsPath, fromRev, toRev); // формируем имя дифф-файла и проверяем его на наличие
        }

        /// <summary>
        /// Возвращает разность между количеством строк кода в указанном файле в ревизии toRev и в ревизии fromRev
        /// </summary>
        public int SlocDiff(string filePath)
        {
            var diffFileStreamReader = OpenDiffFile();
            
            var topic = new Regex(String.Format(@"^Index:.+{0}$", filePath), RegexOptions.IgnoreCase | RegexOptions.Compiled);
            var index = new Regex(@"^Index:\s", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            var inf = new Regex(@"^@@..\d+,(\d+)..\d+,(\d+).@@$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            var infLeft = new Regex(@"^@@..\d+..\d+,(\d+).@@$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            var infRight = new Regex(@"^@@..\d+,(\d+)..\d+.@@$", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            string diffLine;
            do diffLine = diffFileStreamReader.ReadLine();
            while (!topic.IsMatch(diffLine));

            var result = 0;
            while (!string.IsNullOrEmpty(diffLine = diffFileStreamReader.ReadLine()) && !index.IsMatch(diffLine))
            {
                if (inf.IsMatch(diffLine))
                {
                    var m = inf.Match(diffLine);
                    result += int.Parse(m.Groups[2].Value) - int.Parse(m.Groups[1].Value);
                }
                if (infLeft.IsMatch(diffLine))
                    result += int.Parse(infLeft.Match(diffLine).Groups[1].Value);
                if (infRight.IsMatch(diffLine))
                    result -= int.Parse(infRight.Match(diffLine).Groups[1].Value);
            }

            diffFileStreamReader.Close();
            return result;
        }

        private static StreamReader OpenDiffFile()
        {
            if (!File.Exists(diffFileName))
            {
                Console.Error.WriteLine("Unpredictable removal of diff files! Please Re-download diff files.");
                Environment.Exit(1);
            }

            return File.OpenText(diffFileName);
        }
    }
}
